﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog opendialog = new OpenFileDialog();
            if (opendialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }


            IntPtr _connection = IntPtr.Zero;
            if (SqliteDLL.sqlite3_open(opendialog.FileName, out _connection) != SqliteDLL.SQLITE_OK)
                return;

            if (SqliteDLL.sqlite3_key(_connection, textBox1.Text, textBox1.Text.Length) != SqliteDLL.SQLITE_OK)
                return;

            IntPtr stmHandle;
            string strsql = "select * from menu";
            if (SqliteDLL.sqlite3_prepare_v2(_connection, strsql, strsql.Length, out stmHandle, IntPtr.Zero) != SqliteDLL.SQLITE_OK)
                return;

            int iColumnCount = SqliteDLL.sqlite3_column_count(stmHandle);
            DataTable dataTableTmp = new DataTable();
            for (int i = 0; i < iColumnCount; i++)
            {
                string columnName = Marshal.PtrToStringAnsi(SqliteDLL.sqlite3_column_name(stmHandle, i));
                dataTableTmp.Columns.Add(columnName);
            }

            /* 获取每行数据 */
            while (SqliteDLL.sqlite3_step(stmHandle) == SqliteDLL.SQLITE_ROW)
            {
                DataRow dataRowTmp = dataTableTmp.NewRow();
                for (int i = 0; i < iColumnCount; i++)
                {
                    byte[] byteArrayUnicode = Encoding.Unicode.GetBytes(Marshal.PtrToStringUni(SqliteDLL.sqlite3_column_text(stmHandle, i))); //转成UNICODE编码
                    dataRowTmp[i] = Encoding.UTF8.GetString(byteArrayUnicode);
                }
                dataTableTmp.Rows.Add(dataRowTmp);
            }

            SqliteDLL.sqlite3_finalize(stmHandle);
            SqliteDLL.sqlite3_close(_connection);

            dataGridView1.DataSource = dataTableTmp;
        }
    }
}
